import socket


def request_handler(client_socket):
    request_data = client_socket.recv(1024)
    if not request_data:
        client_socket.close()
        return
        # 响应报文
    response_line = "HTTP/1.1 200 OK\r\n"  # 响应行
    response_header = "Server:Python20WS/2.1\r\nContent-Type:text/html; charset=utf-8\r\n"  # 响应头
    response_blank = "\r\n"  # 响应空行
    response_body = "你好 世界！"  # 响应的主体内容
    response_data = response_line + response_header + response_blank + response_body

    # 发送响应报文
    client_socket.send(response_data.encode("utf-8"))

    # 关闭当前连接
    client_socket.close()


def start_web_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建套接字
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)  # 设置地址重用
    server_socket.bind(("", 8800))  # 绑定端口
    server_socket.listen(128)  # 最大接入数

    while True:
        new_client_socket, ip_port = server_socket.accept()
        print(f"客户端连接:\tip:{ip_port[0]} 端口:{ip_port[1]}")
        request_handler(new_client_socket)  # 响应函数


if __name__ == '__main__':
    start_web_server()
